package cn.haoxsf.app.system.dto;

import cn.haoxsf.app.common.api.enums.UserExceptionEnum;
import cn.haoxsf.app.common.util.ToolUtil;
import cn.haoxsf.app.system.entity.Member;
import cn.haoxsf.app.system.entity.Permission;
import cn.haoxsf.app.system.service.IMemberService;
import cn.haoxsf.app.system.service.IRedisService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @program: app
 * @description:
 * @author: Ele qvbanfm@qq.com
 * @create: 2020-01-08 11:49
 **/
@Component
public class MemberDetailsService implements UserDetailsService {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IRedisService redisService;

    @Override
    public LoginUser loadUserByUsername(String s) throws UsernameNotFoundException {
        //查询redis
        String string = redisService.getString(s);
        Member member = null;
        if (ToolUtil.isEmpty(string)) {
            //没有缓存用户
            member = memberService.getMemberByUsername(s);//按照用户名查询
            if (ToolUtil.isEmpty(member)) {
                member = memberService.getMemberByOpenId(s);//按照openid名查询
                if (ToolUtil.isEmpty(member)) {
                    throw new UsernameNotFoundException(UserExceptionEnum.NOT_USERS.getMsg());
                }
            }
            List<Permission> permissionList = memberService.getPermissionList(member.getId());
            //缓存用户
            LoginUser loginUser = new LoginUser(member, permissionList);
            RedisUser redisUser = new RedisUser();
            redisUser.setMember(member);
            redisUser.setPermissionList(permissionList);
            redisService.setString(s, JSON.toJSONString(redisUser), 10);
            return loginUser;
        } else {
            RedisUser redisUser = JSON.parseObject(string, RedisUser.class);
            return new LoginUser(redisUser.getMember(), redisUser.getPermissionList());
        }
    }
}
